package com.power.sifa.approve.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollectionUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.domain.YesNo;
import com.plf.common.utils.ExcelUtil;
import com.power.sifa.approve.api.IApl_admreviewFeign;
import com.power.sifa.approve.model.*;
import com.power.sifa.approve.model.pageInfo.Apl_admreviewPageInfo;
import com.power.sifa.approve.model.pojo.vo.AdmirePersonVO;
import com.power.sifa.approve.service.Apl_admreviewService;
import com.power.sifa.approve.service.Apl_applicantService;
import com.power.sifa.approve.service.Apl_thirdperService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;



/**
 *   行政复议申请控制器
 */

@Slf4j
//@PowerLog
@RestController
@Api(value = "Apl_admreviewController",tags={"行政复议申请"})
public class Apl_admreviewController implements IApl_admreviewFeign{

    @Resource
    private Apl_admreviewService apl_admreviewService;

    @Resource
    private Apl_applicantService apl_applicantService;

    @Resource
    private Apl_thirdperService apl_thirdperService;

    @Override
    @ApiOperation("查询行政复议申请分页列表")
    @SaCheckPermission("apl_admreview_list")
    public ResponseDTO list(Apl_admreviewPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        Page<Apl_admreview> page = this.apl_admreviewService.findAll(pageInfo);
        List list = new ArrayList();
        if (!page.isEmpty()) {
            for (Apl_admreview apl_admreview : page) {
                apl_admreview.geneText();
                list.add(apl_admreview);
            }
        }
        PageDataResponse p = new PageDataResponse(list, page.getTotalElements(), page.getSize(), pageInfo.getPageNumber()<=1 ? 1 : pageInfo.getPageNumber());
        return ResponseDTO.succData(p);
    }

    @Override
    @ApiOperation("查看行政复议申请")
    @SaCheckPermission("apl_admreview_view")
    public ResponseDTO view(String id) {
        Assert.notNull(id, "id不能为空");
        Apl_admreview apl_admreview  = apl_admreviewService.getById(id);
        if (apl_admreview != null) {
            apl_admreview.geneText();
        }
        return ResponseDTO.succData(apl_admreview);
    }

    @Override
    @ApiOperation("删除行政复议申请")
    @SaCheckPermission("apl_admreview_del")
    public ResponseDTO delete(String id) {
        Assert.notNull(id, "id不能为空");
        apl_admreviewService.removeById(id);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation("保存或修改行政复议申请")
    @SaCheckPermission("apl_admreview_save")
    public ResponseDTO save(Apl_admreview apl_admreview) {
        Assert.notNull(apl_admreview, "apl_admreview不能为空");
        apl_admreviewService.saveOrUpdate(apl_admreview);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation(value="批量删除行政复议申请")
    @SaCheckPermission("apl_admreview_del")
    public ResponseDTO batchDel(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "ids不能为空");
        List<Integer> list = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        apl_admreviewService.removeByIds(list);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation(value="导出excel")
    @SaCheckPermission("apl_admreview_list")
    public void output(HttpServletResponse response, Apl_admreviewPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo不能为空");
        String title = "行政复议申请";
        String[] heads = {"applyid","申请人","是否委托代理人","代理人","被申请人","被申请人的行政区划","是否行政不作为","申请人曾要求被申请人履行何种法定职责",
                "要求被申请人履行法定职责日期","要求被申请人履行法定职责的方式","行政复议请求（不作为）","行政行为名称","行政行为文号","知道该行政行为日期","行政行为知晓方式",
                "行政复议请求（行政作为）","是否申请规范性文件审查","是否就同一事项向其他行政复议机关提出申请","是否就同一事项像人民法院提起诉讼","是否申请国家赔偿","申请赔偿金额","是否申请进行调解"
                ,"事实和理由","行政复议状态","调解结果","案件收到时间"};
        String[] fields = {"id","applyname","isagent","agentname","targetname","targetadid","isomission","omcontent",
                "omdate","omway","omrequest","prname","prcode","prdate","prway","prrequest","ischeckdoc","isexreview"
                ,"isexlawsuit","ispay","paymoney","ismediate","reason","status","mediateresult","receivetime"};
        Page<Apl_admreview> page = this.apl_admreviewService.findAll(pageInfo);
        ExcelUtil.exportXls(title, heads, fields, page.getContent(), response);
    }

    @Override
    @ApiOperation(value="导出excel模板")
    public void exportExcelTemplate(HttpServletResponse response) {
        String title = "行政复议申请";
        //id自增或list从表可自行删除，需与导入项一致
        String[] heads = {"applyid","申请人","是否委托代理人","代理人","被申请人","被申请人的行政区划","是否行政不作为","申请人曾要求被申请人履行何种法定职责","要求被申请人履行法定职责日期","要求被申请人履行法定职责的方式","行政复议请求（不作为）","行政行为名称","行政行为文号","知道该行政行为日期","行政行为知晓方式","行政复议请求（行政作为）","是否申请规范性文件审查","是否就同一事项向其他行政复议机关提出申请","是否就同一事项像人民法院提起诉讼","是否申请国家赔偿","申请赔偿金额","是否申请进行调解","事实和理由","行政复议状态","调解结果","案件收到时间"};
        ExcelUtil.exportXls(title, heads, null, null, response);
    }

	@Override
	@ApiOperation(value="导入excel")
	public ResponseDTO importExcel(MultipartFile file) throws IOException {
        Assert.notNull(file, "file不能为空");
        //id自增或list从表可自行删除，需与下载的模板中导入项一致
        String[] fields = {"id","applyname","isagent","agentname","targetname","targetadid","isomission","omcontent",
                "omdate","omway","omrequest","prname","prcode","prdate","prway","prrequest","ischeckdoc","isexreview"
                ,"isexlawsuit","ispay","paymoney","ismediate","reason","status","mediateresult","receivetime"};
        List<Apl_admreview> list = (List<Apl_admreview>)ExcelUtil.Import(fields, file, Apl_admreview.class);
        if(!CollectionUtils.isEmpty(list)) {
            this.apl_admreviewService.saveAll(list);
        }
        return ResponseDTO.succ();
	}


    @Override
    @ApiOperation("查看行政复议申请-案件录入-案件列表")
    public ResponseDTO queryByPage(Apl_admreviewPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        PageDataResponse result  = apl_admreviewService.findJoinAll(pageInfo);
        return ResponseDTO.succData(result);
    }

    /**
     * 行政复议联-根据相似度查询对应的相似行政复议申请
     * @param applyId
     * @return
     */

    @Override
    @ApiOperation("行政复议联-根据相似度查询对应的相似行政复议申请")
    public ResponseDTO getSimilarityReview(String applyId) {
        Assert.notNull(applyId, "行政复议申请applyId不能为空");
        List<Apl_admreview_similarity> similarityList = apl_admreviewService.getSimilarityReview(applyId);
        return ResponseDTO.succData(similarityList);
    }

    /**
     * 行政复议联-修改对应applyid的被申请人
     * @param applyid
     * @param targetname
     * @param targetadid
     * @return
     */
    @Override
    @ApiOperation("行政复议联-修改对应applyid的被申请人")
    public ResponseDTO updateTargetName(String applyid, String targetname, String targetadid, Map<String,Apl_target> targetInfo) {
        Assert.notNull(applyid, "行政复议申请applyId不能为空");
        Assert.notNull(targetname, "行政复议申请被申请人不能为空");
        Assert.notNull(targetadid, "行政复议申请被申请人id不能为空");
        try {
            apl_admreviewService.updateTargetName(applyid, targetname, targetadid, targetInfo);
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return ResponseDTO.wrap(500, "更新被申请人失败");
        }
    }

    /**
     * 更新被申请人是否答复字段和答复时限
     * @param applyid
     * @param reply
     * @return
     */
    @Override
    public ResponseDTO updateTargetReply(String applyid, Boolean reply) {
        Assert.notNull(applyid, "行政复议申请applyId不能为空");
        apl_admreviewService.updateTargetReply(applyid, reply);
        return ResponseDTO.succ();
    }

    /**
     * 获取对应的行政复议子状态
     * @param applyid
     * @return
     */
    @Override
    public ResponseDTO getSonStatusByIds(String applyid) {
        Assert.notNull(applyid, "行政复议申请applyId不能为空");
        Apl_admreview apl_admreview = apl_admreviewService.getById(applyid);
        List<String> sonStatus = apl_admreviewService.getSonStatusByIds(applyid);
        Map<String,Object> resultObj = new HashMap<>();
        resultObj.put("sonStatus", sonStatus);
        resultObj.put("isrest", apl_admreview.getIsrest().equals(YesNo.YES) ? true : false);
        resultObj.put("reason", apl_admreview.getReason());
        // 决定类型
        resultObj.put("decisiontype", apl_admreview.getDecisiontype());
        resultObj.put("decisiontypeid", apl_admreview.getDecisiontypeid());
        resultObj.put("decisiontypename", apl_admreview.getDecisiontypename());
        resultObj.put("admreview", apl_admreview);
        return ResponseDTO.succData(resultObj);
    }

    /**
     * 行政复议归档记录分页查询-查询待归档和已归档的数据
     * @param pageInfo
     * @return
     */
    @Override
    public ResponseDTO queryArchivePage(Apl_admreviewPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        PageDataResponse result  = apl_admreviewService.queryArchivePage(pageInfo);
        return ResponseDTO.succData(result);
    }

    @Override
    public ResponseDTO getAdmirePersonInfo(String applyid) {
        Assert.notNull(applyid, "applyid参数不能为空");
        Apl_admreview apl_admreview = apl_admreviewService.getById(applyid);
        // apl_admreview.geneText();
        List<Apl_applicant> applicantList = apl_applicantService.getApplicantByApplyid(applyid);
        applicantList.stream().forEach(item -> item.geneText());
        List<Apl_thirdper> thirdperList = apl_thirdperService.getThirdListByApplyid(applyid);
        thirdperList.stream().forEach(item -> item.geneText());
        return ResponseDTO.succData(AdmirePersonVO.builder().apl_admreview(apl_admreview)
                .applicantList(applicantList).thirdperList(thirdperList).build());
    }

    @Override
    public ResponseDTO updatesAcceptExamineUsers(String id, String firstuserid, String firstusername, String seconduserid, String secondusername) {
        try {
            this.apl_admreviewService.updatesAcceptExamineUsers(id, firstuserid, firstusername, seconduserid, secondusername);
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("updatesAcceptExamineUsers 更新第一/第二立案审查人信息失败 ->  msg[{}]", e.getMessage());
            return ResponseDTO.wrap(500, "更新第一/第二立案审查人信息失败");
        }
    }


    @Override
    public ResponseDTO updatesHearExamineUsers(List<String> ids, String firstuserid, String firstusername, String seconduserid, String secondusername) {
        try {
            Assert.notNull(ids, "修改id不能为空");
            if (CollectionUtil.isNotEmpty(ids)) {
                ids.stream().forEach(id -> {
                    this.apl_admreviewService.updatesHearExamineUsers(id, firstuserid, firstusername, seconduserid, secondusername);
                });
                return ResponseDTO.succ();
            }

            return ResponseDTO.wrap(500, "更新第一/第二立案审查人信息失败,id为空");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("updatesHearExamineUsers 更新第一/第二立案审查人信息失败 ->  msg[{}]", e.getMessage());
            return ResponseDTO.wrap(500, "更新第一/第二立案审查人信息失败");
        }
    }

    /**
     * 通过applyic查询申请人信息
     *
     * @param applyid
     * @return
     */
    @Override
    public ResponseDTO getAdmreviewInfoAndCheckDoc(String applyid) {
        try {
            return ResponseDTO.succData(this.apl_admreviewService.getAdmreviewInfoAndCheckDoc(applyid));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDTO.wrap(500, "查询被申请人信息失败");
        }
    }

}
